package oss

import (
	"bytes"
	"encoding/base64"
	"net/http"

	"alolang.org.cn/api/server/config"
	"alolang.org.cn/api/server/log"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func UploadFileFromBase64(b64string string, filename string) (url string, err error) {
	client, err := oss.New(config.Server.OSS.EndPoint, config.Server.OSS.AccessKeyID, config.Server.OSS.AccessKeySecret)
	if err != nil {
		log.Logger.Errorln("Failed to get OSS client: ", err)
		return "", err
	}
	bucket, err := client.Bucket(config.Server.OSS.BucketName)
	if err != nil {
		log.Logger.Errorln("Failed to get OSS bucket: ", err)
		return "", err
	}
	file, err := base64.RawStdEncoding.DecodeString(b64string)
	if err != nil {
		log.Logger.Errorln("Failed to decode base64: ", err)
		return "", err
	}
	err = bucket.PutObject(filename, bytes.NewReader(file))
	if err != nil {
		log.Logger.Errorln("Failed to upload file: ", err)
		return "", err
	}
	return "https://" + config.Server.OSS.BucketName + "." + config.Server.OSS.EndPoint + "/" + filename, nil
}

func UploadFileFromHTTP(path string, filename string) (url string, err error) {
	resp, err := http.Get(path)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	client, err := oss.New(config.Server.OSS.EndPoint, config.Server.OSS.AccessKeyID, config.Server.OSS.AccessKeySecret)
	if err != nil {
		log.Logger.Errorln("Failed to get OSS client: ", err)
		return "", err
	}
	bucket, err := client.Bucket(config.Server.OSS.BucketName)
	if err != nil {
		log.Logger.Errorln("Failed to get OSS bucket: ", err)
		return "", err
	}
	err = bucket.PutObject(filename, resp.Body)
	if err != nil {
		log.Logger.Errorln("Failed to upload file: ", err)
		return "", err
	}
	return "https://" + config.Server.OSS.BucketName + "." + config.Server.OSS.EndPoint + "/" + filename, nil
}
